Toggle heading
Bold
Italicize
Format as code
Insert link
Add blockquote
Add numbered list
Add bulleted list
Add horizontal rule
LaTeX
Insert emoji
Reposition markdown preview
#Data Types and Structure Assignment
Mutable Data Types
Can be changed or modified after creation.
You can update, add, or remove elements without creating a new object.
Examples in Python: list, set, dict
Immutable Data Types
Cannot be changed once created.
Any modification creates a new object in memory.
Examples in Python: int, float, string, tuple
Here are the main differences between lists and tuples in Python:
Mutability: Lists are mutable (can be changed), Tuples are immutable (cannot be changed).
Syntax: Lists use square brackets [], Tuples use parentheses ().
Performance: Tuples are faster than lists because they are fixed.
Functions/Methods: Lists have more built-in methods (like append(), remove()), Tuples have fewer.
Use case: Lists are used when data may change, Tuples are used when data must remain constant.
In Python, a dictionary stores data in the form of key–value pairs.
Each item has a key (unique identifier) and a value (data associated with the key).
Dictionaries use a hashing mechanism, so keys are stored in a way that makes lookup very fast.
Keys must be immutable (like strings, numbers, or tuples), while values can be of any type.
Data is enclosed in curly braces {}.
'''
student = {"name": "Alex", "age": 20, "grade": "A"}
print(student["name"]) # Output: Alex
'''
No Duplicates Needed → Sets automatically remove duplicate values.
Fast Membership Checking → Checking if an item exists in a set is much faster than in a list (because sets use hashing).
Set Operations → Sets support mathematical operations like union (|), intersection (&), and difference (-), which lists don’t directly support.
'''
nums = [1, 2, 2, 3, 4]
unique_nums = set(nums)
print(unique_nums) # Output: {1, 2, 3, 4}
'''
'''
text = "Hello"
'''
Difference between String and List
Data type: String stores only characters; List can store mixed data types (numbers, strings, etc.).
Mutability: Strings are immutable (cannot be changed after creation), Lists are mutable (can be changed).
Syntax: Strings use quotes, Lists use square brackets [].
Operations: Both support indexing and slicing, but only lists allow item assignment.
'''
# String (immutable)
s = "hello"
# s[0] = "H" # Error (strings cannot be modified)
# List (mutable)
l = ["h", "e", "l", "l", "o"]
l[0] = "H"
print(l) # Output: ['H', 'e', 'l', 'l', 'o']
'''
How this helps:
Prevents accidental modification of data.
Useful for storing constant values that should not be altered.
Can be used as keys in dictionaries because their immutability makes them hashable.
'''
coordinates = (10, 20)
# coordinates[0] = 15 # Error, tuple cannot be modified
'''
A hash table is a data structure that stores data in key–value pairs and uses a hash function to compute an index (called a hash) for each key. This makes data lookup, insertion, and deletion very fast.
How it relates to Python dictionaries:
Python dictionaries are implemented using hash tables.
Each key in a dictionary is hashed to determine where its value will be stored.
This allows quick access to values using their keys.
Keys must be immutable (like strings, numbers, or tuples) so that their hash value remains constant.
'''
student = {"name": "Alex", "age": 20}
print(student["name"]) # Output: Alex
'''
Yes, lists in Python can contain different data types in the same list.
Lists can store integers, strings, floats, booleans, or even other lists together.
This makes them very flexible for storing mixed data.
'''
my_list = [10, "Hello", 3.14, True]
print(my_list)
# Output: [10, 'Hello', 3.14, True]
'''
Reasons for immutability:
Memory Efficiency – Immutable strings can be shared safely in memory without risk of accidental changes.
Hashing – Strings are hashable and can be used as dictionary keys or set elements. If they were mutable, their hash value could change, breaking data structures.
Safety and Predictability – Prevents accidental modification of data, ensuring consistent behavior in programs.
'''
s = "hello"
# s[0] = "H" # Error: strings cannot be modified
'''
Dictionaries offer several advantages over lists for certain tasks because they store data as key–value pairs:
Fast Lookups – Accessing a value by its key is much faster than searching through a list.
Unique Keys – Keys are unique, which prevents duplicate entries for identifiers.
Clear Mapping – Keys provide meaningful names for values, making data easier to understand.
Flexible Data Access – You can directly retrieve, update, or delete a value using its key instead of index.
Supports Complex Operations – Dictionaries are ideal for tasks like counting items, grouping data, or representing structured data.
'''
# Using a list
students = ["Alice", "Bob", "Charlie"]
# Find age of Bob? Need separate list or search
# Using a dictionary
students = {"Alice": 20, "Bob": 22, "Charlie": 19}
print(students["Bob"]) # Output: 22 (direct lookup)
'''
Coordinates should not be modified, so using a tuple ensures data integrity.
Tuples are also faster and can be used as dictionary keys if needed.
'''
location = (40.7128, -74.0060) # New York City coordinates
'''
In Python, sets automatically remove duplicate values.
A set stores only unique elements, so if you try to add a duplicate, it will be ignored.
This makes sets useful for finding unique items or eliminating duplicates from a collection.
'''
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers) # Output: {1, 2, 3, 4, 5}
'''
Lists
Checks if a value exists anywhere in the list.
Returns True if the value is present, False otherwise.
'''
my_list = [1, 2, 3]
print(2 in my_list) # Output: True
print(5 in my_list) # Output: False
'''
Dictionaries
Checks if a key exists in the dictionary (not the value).
Returns True if the key is present, False otherwise.
'''
my_dict = {"a": 10, "b": 20}
print("a" in my_dict) # Output: True
print(10 in my_dict) # Output: False (checks keys, not values)
'''
Why:
Tuples are immutable, meaning once a tuple is created, its contents cannot be changed, added, or removed.
This ensures data integrity and allows tuples to be used as dictionary keys or stored in sets.
'''
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # Error: tuples cannot be modified
'''
Use Case:
Storing complex structured data, like student records, employee details, or product information.
Useful in scenarios where each key maps to multiple attributes.
'''
students = {
"Alice": {"age": 20, "grade": "A"},
"Bob": {"age": 22, "grade": "B"},
"Charlie": {"age": 19, "grade": "A"}
}
# Accessing Bob's grade
print(students["Bob"]["grade"]) # Output: B
'''
Time Complexity:
Average Case: O(1) → Constant time (direct lookup using key’s hash).
Worst Case: O(n) → Rare, happens only when many keys hash to the same index (hash collisions).
'''
my_dict = {"a": 1, "b": 2, "c": 3}
print(my_dict["b"]) # Access in O(1) time
'''
Lists are preferred over dictionaries in Python when:
Order Matters – Lists maintain the order of elements, which is useful for sequences.
Index-based Access – When you want to access elements by position rather than a key.
Simple Collections – When you just need a collection of items without key–value mapping.
-Iteration Over All Elements – Easy to loop through elements in order.
'''
fruits = ["apple", "banana", "cherry"]
print(fruits[1]) # Output: banana (access by index)
'''
How it affects data retrieval:
Direct Access by Key – You cannot rely on the order of keys; you must access values using their specific keys.
Iteration Order (pre-3.7) – Iterating over the dictionary may return keys in an arbitrary order.
No Indexing – Unlike lists, you cannot access dictionary items by position (e.g., dict[0] is invalid).
'''
my_dict = {"a": 1, "b": 2, "c": 3}
for key in my_dict:
print(key, my_dict[key])
'''
Access Method:
List → Access elements by index.
Dictionary → Access elements by key.
Speed:
List → Searching for a value takes O(n) time.
Dictionary → Key lookup is usually O(1) (very fast).
Order:
List → Maintains the order of elements.
Dictionary → Unordered (before Python 3.7); ordered by insertion (Python 3.7+).
Use Case:
List → Sequential data, iteration by position.
Dictionary → Fast access to values using meaningful keys.
'''
# Creating a string with your name
name = "Khushnoor Alam"
# Printing the string
print(name) #output = Khushnoor Alam
'''
'''
# String
text = "Hello World"
# Finding length
length = len(text)
# Printing the length
print("Length of the string:", length) #output = Length of the string: 11
'''
'''
# String
text = "Python Programming"
# Slicing the first 3 characters
first_three = text[:3]
# Printing the result
print(first_three) #output = Pyt
'''
'''
# String
text = "hello"
# Converting to uppercase
upper_text = text.upper()
# Printing the result
print(upper_text) #output = HELLO
'''
'''
# Original string
text = "I like apple"
# Replacing "apple" with "orange"
new_text = text.replace("apple", "orange")
# Printing the result
print(new_text) #output = I like orange
'''
'''
# Creating a list
numbers = [1, 2, 3, 4, 5]
# Printing the list
print(numbers) #output = [1, 2, 3, 4, 5]
'''
'''
# Original list
numbers = [1, 2, 3, 4]
# Appending 10 to the list
numbers.append(10)
# Printing the updated list
print(numbers) #output = [1, 2, 3, 4, 10]
'''
'''
# Original list
numbers = [1, 2, 3, 4, 5]
# Removing the number 3
numbers.remove(3)
# Printing the updated list
print(numbers) #output = [1, 2, 4, 5]
'''
'''# List
letters = ['a', 'b', 'c', 'd']
# Accessing the second element (index 1)
second_element = letters[1]
# Printing the result
print(second_element) #output = b
'''
'''
# Original list
numbers = [10, 20, 30, 40, 50]
# Reversing the list
numbers.reverse()
# Printing the reversed list
print(numbers) #output = [50, 40, 30, 20, 10]
'''
'''
# Creating a tuple
numbers = (100, 200, 300)
# Printing the tuple
print(numbers) #output = (100, 200, 300)
'''
'''
# Tuple
colors = ('red', 'green', 'blue', 'yellow')
# Accessing the second-to-last element
second_last = colors[-2]
# Printing the result
print(second_last) #output = blue
'''
'''
# Tuple
numbers = (10, 20, 5, 15)
# Finding the minimum number
min_number = min(numbers)
# Printing the result
print(min_number) #output = 5
'''
'''
# Tuple
animals = ('dog', 'cat', 'rabbit')
# Finding the index of "cat"
index_cat = animals.index('cat')
# Printing the result
print(index_cat) #output = 1
'''
'''
# Creating a tuple
fruits = ('apple', 'banana', 'mango')
# Checking if "kiwi" is in the tuple
is_kiwi_present = 'kiwi' in fruits
# Printing the result
print(is_kiwi_present) #output = False
'''
'''# Creating a set
letters = {'a', 'b', 'c'}
# Printing the set
print(letters) #output = {'a', 'b', 'c'}
'''
'''
# Original set
numbers = {1, 2, 3, 4, 5}
# Clearing the set
numbers.clear()
# Printing the empty set
print(numbers) #output = set()
'''
'''
# Original set
numbers = {1, 2, 3, 4}
# Removing the element 4
numbers.remove(4)
# Printing the updated set
print(numbers) #output = {1, 2, 3}
'''
'''
# Original set
numbers = {1, 2, 3, 4}
# Removing the element 4
numbers.remove(4)
# Printing the updated set
print(numbers) #output = {1, 2, 3}
'''
'''
# Two sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}
# Finding intersection
intersection = set1 & set2 # or set1.intersection(set2)
# Printing the result
print(intersection) #output ={2, 3}
'''
'''
# Creating a dictionary
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# Printing the dictionary
print(person) #output = {'name': 'Alice', 'age': 25, 'city': 'New York'}
'''
'''# Original dictionary
person = {'name': 'John', 'age': 25}
# Adding new key-value pair
person['country'] = 'USA'
# Printing the updated dictionary
print(person) #output = {'name': 'John', 'age': 25, 'country': 'USA'}
'''
'''
# Dictionary
person = {'name': 'Alice', 'age': 30}
# Accessing the value of key "name"
name_value = person['name']
# Printing the result
print(name_value) #output = Alice
'''
'''# Original dictionary
person = {'name': 'Bob', 'age': 22, 'city': 'New York'}
# Removing the key "age"
person.pop('age') # or del person['age']
# Printing the updated dictionary
print(person) #output = {'name': 'Bob', 'city': 'New York'}
'''
'''
# Dictionary
person = {'name': 'Alice', 'city': 'Paris'}
# Checking if the key "city" exists
key_exists = 'city' in person
# Printing the result
print(key_exists) #output = True
'''
''''# Creating a list
my_list = [1, 2, 3]
# Creating a tuple
my_tuple = (4, 5, 6)
# Creating a dictionary
my_dict = {'name': 'Alice', 'age': 25}
# Printing all
print("List:", my_list)
print("Tuple:", my_tuple)
print("Dictionary:", my_dict) #output = List: [1, 2, 3]
Tuple: (4, 5, 6)
Dictionary: {'name': 'Alice', 'age': 25}
'''
'''
import random
# Creating a list of 5 random numbers between 1 and 100
numbers = [random.randint(1, 100) for _ in range(5)]
# Sorting the list in ascending order
numbers.sort()
# Printing the sorted list
print(numbers)
#output = [12, 27, 45, 63, 88]
'''
'''
# Creating a list of strings
fruits = ["apple", "banana", "cherry", "date", "mango"]
# Accessing the element at index 3 (fourth element)
element = fruits[3]
# Printing the result
print(element)
#output = date
'''
'''
# Two dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
# Combining dictionaries
combined_dict = {**dict1, **dict2} # Using dictionary unpacking
# Printing the result
print(combined_dict)
#output = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
'''
Start coding or generate with AI.
Start coding or generate with AI.
Start coding or generate with AI.
Double-click (or enter) to edit
Double-click (or enter) to edit
Start coding or generate with AI.
Start coding or generate with AI.
2. Write a code to find the length of the string "Hello World".
Start coding or generate with AI.
Start coding or generate with AI.
Double-click (or enter) to edit
Start coding or generate with AI.